package com.saltedfish.tool;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.saltedfish.tool.constant.IntConstant;
import com.saltedfish.tool.constant.StringConstant;
import com.saltedfish.tool.handler.CrashHandler;
import com.saltedfish.tool.model.User;
import com.saltedfish.tool.ui.user.LoginActivity;
import com.saltedfish.tool.util.SharePreferceUtils;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.IOException;

import cn.droidlover.xdroidmvp.BaseApplication;
import cn.droidlover.xdroidmvp.bean.BaseModel;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.NetProvider;
import cn.droidlover.xdroidmvp.net.RequestHandler;
import cn.droidlover.xdroidmvp.net.XApi;
import cn.droidlover.xdroidmvp.util.AppUtil;
import okhttp3.CookieJar;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by zhanggongyi on
 */

public class App extends BaseApplication {

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler.getInstance().init(this);
        initGlide(this);
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        StringConstant.wx_api = WXAPIFactory.createWXAPI(getApplicationContext(), StringConstant.APP_ID, true);
        // 将应用的appId注册到微信
        StringConstant.wx_api.registerApp(StringConstant.APP_ID);

        XApi.registerProvider(new NetProvider() {

            @Override
            public Interceptor[] configInterceptors() {
                Interceptor[] interceptors = new Interceptor[1];
                interceptors[0] = new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        String deviceId  = SharePreferceUtils.getString("device_id");
                        String token = SharePreferceUtils.getString(User.USER_TOKEN);
                        String userId = SharePreferceUtils.getString(User.USER_ID);

                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
//                                .header("deviceId", deviceId)
                                .header("c-token", token)
                                .header("c-user-id", userId)
                               .header("device-type", "android")
                                .header("version-name", AppUtil.getVersionName(BaseApplication.getInstance()));

                        Request request = requestBuilder.build();
                        Response response = chain.proceed(request);
                        return getNewResponse(response);
                    }
                };
                return interceptors;
            }

            @Override
            public void configHttps(OkHttpClient.Builder builder) {

            }

            @Override
            public CookieJar configCookie() {
                return null;
            }

            @Override
            public RequestHandler configHandler() {
                return null;
            }

            @Override
            public long configConnectTimeoutMills() {
                return 0;
            }

            @Override
            public long configReadTimeoutMills() {
                return 0;
            }

            @Override
            public boolean configLogEnable() {
                return true;
            }

            @Override
            public boolean handleError(NetError error) {
                if(error.getType() == IntConstant.ERROR_900){
                    User.getInstance().logoutSuccess();
                    Intent intent = new Intent(App.getInstance(), LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    App.getInstance().startActivity(intent);
                } else {
                    if (!TextUtils.isEmpty(error.getErrorMessage())) {
                        Toast.makeText(getApplicationContext(), error.getErrorMessage(), Toast.LENGTH_LONG).show();
                    }
                }
                return false;
            }

            @Override
            public boolean dispatchProgressEnable() {
                return false;
            }
        });


        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }



    private Response getNewResponse(final Response response) {
        try {
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                String resp = body.string();
                Gson gson = new Gson();
                BaseModel model = gson.fromJson(resp, BaseModel.class);
                if (model != null && model.isError()) {
                    model.result = new JSONObject();
                    body = ResponseBody.create(mediaType, gson.toJson(model));
                } else {
                    body = ResponseBody.create(mediaType, resp);
                }
                return response.newBuilder().body(body).build();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    //初始化Glide
    public void initGlide(Context cxt) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //下面用到的url最好是不存在的，目的只是为了初始化Glide
                Glide.with(cxt);
            }
        }).start();

    }

}
